package org.hrqing.chess.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * json处理的工具类
 */
public class JSON {

    private static final ObjectMapper mapper = new ObjectMapper();

    static{
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        mapper.registerModule(javaTimeModule);
    }

    /**
     * 解析json数组，返回指定泛型的List集合
     */
    public static <T> List<T> parseArray(String text, Class<T> clazz){

        List<T> result;
        try {
            JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class,clazz);
            result = mapper.readValue(text, javaType);
        } catch (IOException e) {
            throw new RuntimeException("json数组解析失败",e);
        }
        return result;
    }

    /**
     * 把对象转化为json字符串
     */
    public static String toJSONString(Object object){
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("json对象转string失败",e);
        }
    }

    /**
     * 解析json对象字符串，返回对应泛型对象
     */
    public static <T> T parseObject(String text, Class<T> clazz){
        try {
            return mapper.readValue(text,clazz);
        } catch (Exception e) {
            throw new RuntimeException("json字符串转object失败",e);
        }
    }

    /**
     *
     */
    public static <T> T convert(Object object, Class<T> clazz) {
        try {
            return mapper.convertValue(object,clazz);
        } catch (Exception e) {
            throw new RuntimeException("json对象转换失败",e);
        }
    }

    public static JsonNode readTree(String text) {
        try {
            return mapper.readTree(text);
        } catch (Exception e) {
            throw new RuntimeException("json字符串转object失败",e);
        }
    }

}
